import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from 'src/entities/post.entity';
import { User } from 'src/entities/user.entity';
import { CreatePostDTO } from 'src/dto/post/create-post.dto';
import { UpdatePostDTO } from 'src/dto/post/update-post.dto';

@Injectable()
export class PostService {
  constructor(
    @InjectRepository(Post) private postRepository: Repository<Post>,
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  /**
   * 创建新文章
   * @param userId 用户ID
   * @param createPostDTO 文章数据
   * @returns 创建的文章
   */
  async createPost(
    userId: number,
    createPostDTO: CreatePostDTO,
  ): Promise<Post> {
    const user = await this.userRepository.findOneBy({ id: userId });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    const post = this.postRepository.create({
      ...createPostDTO,
      user,
    });

    return this.postRepository.save(post);
  }

  /**
   * 获取文章列表
   * @returns 文章列表
   */
  async getPosts(): Promise<Post[]> {
    return this.postRepository.find({
      relations: ['user'],
      select: {
        user: {
          id: true,
          name: true,
          account: true,
        },
      },
    });
  }

  /**
   * 获取用户文章列表
   * @param userId 用户ID
   * @returns 用户文章列表
   */
  async getPostsByUser(userId: number): Promise<Post[]> {
    const user = await this.userRepository.findOneBy({ id: userId });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    return this.postRepository.find({
      where: { user },
      relations: ['user'],
      select: {
        user: {
          id: true,
          name: true,
          account: true,
        },
      },
    });
  }

  /**
   * 更新文章
   * @param id 文章ID
   * @param userId 用户ID
   * @param updatePostDTO 更新数据
   * @returns 更新后的文章
   */
  async updatePost(
    id: number,
    userId: number,
    updatePostDTO: UpdatePostDTO,
  ): Promise<Post> {
    const post = await this.postRepository.findOne({
      where: { id },
      relations: ['user'],
    });

    if (!post) {
      throw new NotFoundException('文章不存在');
    }

    // 验证文章是否属于当前用户
    if (post.user.id !== userId) {
      throw new NotFoundException('您无权修改此文章');
    }

    // 更新文章信息
    this.postRepository.merge(post, updatePostDTO);
    return this.postRepository.save(post);
  }

  /**
   * 删除文章
   * @param id 文章ID
   * @param userId 用户ID
   */
  async deletePost(id: number, userId: number): Promise<void> {
    const post = await this.postRepository.findOne({
      where: { id },
      relations: ['user'],
    });

    if (!post) {
      throw new NotFoundException('文章不存在');
    }

    // 验证文章是否属于当前用户
    if (post.user.id !== userId) {
      throw new NotFoundException('您无权删除此文章');
    }

    await this.postRepository.remove(post);
  }
}
